Loading or Saving a XAML Resource Dictionary

Here is a rudimentary example of how to load a ResourceDictionary.xaml file and then how to change it and save the changes.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:String x:Key="HW">Hello, World</sys:String>
</ResourceDictionary>
using System;
using System.IO;
using System.Windows;
using System.Windows.Markup;

namespace ReadAndWriteToXaml
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static ResourceDictionary Dictionary;
        public static String XamlFileName = "Dictionary1.xaml";

        public App()
        {
            LoadStyleDictionaryFromFile(XamlFileName);
        }

        /// <summary>
        /// This funtion loads a ResourceDictionary from a file at runtime
        /// </summary>
        public void LoadStyleDictionaryFromFile(string inFileName)
        {
            if (File.Exists(inFileName))
            {
                try
                {
                    using (var fs = new FileStream(inFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // Read in ResourceDictionary File
                        Dictionary = (ResourceDictionary)XamlReader.Load(fs);
                        // Clear any previous dictionaries loaded
                        Resources.MergedDictionaries.Clear();
                        // Add in newly loaded Resource Dictionary
                        Resources.MergedDictionaries.Add(Dictionary);
                    }
                }
                catch
                {
                    // Do something here if file not found
                }
            }
        }

        private void Application_Exit_1(object sender, ExitEventArgs e)
        {
            try
            {
                Dictionary["HW"] += "Hello, back!"; 
                StreamWriter writer = new StreamWriter(XamlFileName);
                XamlWriter.Save(Dictionary, writer);
            }
            catch
            {
                // Do something here if file not found
            }
        }
    }
}

Note: Unfortunately you cannot use two way mode when binding to DynamicResource objects, so editing the xaml file is made a bit more complex. But hopefully, this will help you get started.

Leave a Reply